package org.mixed.core.resource.storage;

import lombok.Getter;
import lombok.Setter;
import org.mixed.core.resource.Info;
import org.mixed.core.resource.ResourceStorage;
import org.mixed.core.resource.info.DataSourceInfo;
import org.mixed.core.utils.IoUtils;
import org.mixed.core.utils.JsonUtils;
import org.mixed.service.MixResourceService;

import java.util.Objects;

@Getter
@Setter
public class DataSourceInfoResourceStorage implements ResourceStorage<DataSourceInfo> {
    private MixResourceService resourceService;

    @Override
    public String folder() {
        return "datasource";
    }

    @Override
    public String suffix() {
        return ".json";
    }

    @Override
    public Class<DataSourceInfo> infoClass() {
        return DataSourceInfo.class;
    }

    @Override
    public boolean requiredScript() {
        return false;
    }

    @Override
    public boolean allowRoot() {
        return true;
    }

    @Override
    public boolean requirePath() {
        return false;
    }

    @Override
    public String buildKey(Info info) {
        return ((DataSourceInfo) info).getKey();
    }

    @Override
    public DataSourceInfo read(byte[] bytes) {
        return JsonUtils.readValue(bytes, DataSourceInfo.class);
    }

    @Override
    public byte[] write(Info info) {
        return JsonUtils.toJsonBytes(info);
    }

    @Override
    public void validate(DataSourceInfo info) {
        ResourceStorage.super.validate(info);
        notBlank(info.getUrl(), DS_URL_REQUIRED);
        notBlank(info.getKey(), DS_KEY_REQUIRED);
        isTrue(resourceService.dsNotMatch(info), DS_KEY_CONFLICT);
    }
}
